package testcase;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.testng.annotations.Test;

import java.io.IOException;

public class HttpClientWithPostCookie {
    @Test
    public void testName() throws IOException {
        // 获取连接客户端工具
        DefaultHttpClient httpClient = new DefaultHttpClient();

        String entityStr = null;
        HttpResponse response = null;

        // 创建POST请求对象
        HttpPost httpPost = new HttpPost("http://localhost:12306/mockPost/with/cookie");

        /*
         * 添加请求参数
         */
        // 创建请求参数
//        List<NameValuePair> list = new LinkedList<NameValuePair>();
//        BasicNameValuePair param1 = new BasicNameValuePair("name", "chengliang");
//        BasicNameValuePair param2 = new BasicNameValuePair("age", "23");




        //添加json格式的参数
        JSONObject param=new JSONObject();
        param.put("name","chengliang");
        param.put("age","23");
//        list.add(param1);
//        list.add(param2);
        // 使用URL实体转换工具
       // UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "UTF-8");
        StringEntity entityParam=new StringEntity(param.toString());
        httpPost.setEntity(entityParam);

        /*
         * 添加请求头信息
         */
        // 浏览器表示
        httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
        // 传输的类型
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        httpPost.addHeader("Cookie","login=true");

        // 执行请求
        response = httpClient.execute(httpPost);
        // 获得响应的实体对象
        HttpEntity entity = response.getEntity();
        // 使用Apache提供的工具类进行转换成字符串
        entityStr = EntityUtils.toString(entity, "UTF-8");

        // System.out.println(Arrays.toString(response.getAllHeaders()));



        // 打印响应内容
        System.out.println(entityStr);

    }

}
